import tools from '../utils/tools.js';
import url from './url.js';
import Qs from 'qs'

function queryData(data) {
	var str = '';
	for (var i in data) {
		str += i + "=" + data[i] + '&';
	}
	if (str) {
		str = '?' + str;
		str = str.substr(0, str.length - 1);
	}
	return str;
}


function get(url, data, cb) {
	uni.request({
		url: url + (queryData(data) ? queryData(data) + '&token=' + uni.getStorageSync('token') : '?token=' +
			uni.getStorageSync('token')),
		method: 'get',
		success: function(res) {
			if (res.statusCode == 200) {
				switch (res.data.code) {
					case 10001:
						uni.showToast({
							title: res.data.toast,
							icon: 'none',
							success() {
								uni.reLaunch({
									url: '/pages/login/index'
								})
							}
						});
						break;
					case 10002:
						uni.showToast({
							title: res.data.toast,
							icon: 'none'
						});
						break;
					case 10004:
						uni.showToast({
							title: res.data.toast,
							icon: 'none'
						});
						break;
					default:
						tools.isFunction(cb) && cb(res.data);
				}
			}
			if (res.statusCode == 422) {
				switch (res.data.code) {
					case 10002:
						uni.showToast({
							title: res.data.toast,
							icon: 'none'
						});
						break;
					default:
				}
			}
		}
	})
}

function post(url, data, cb) {
	uni.request({
		url: url,
		method: 'post',
		header: {
			"content-type": "application/x-www-form-urlencoded"
		},
		data: Qs.stringify(data) + '&token=' + uni.getStorageSync('token'),
		success: function(res) {
			if (res.statusCode == 200) {
				switch (res.data.code) {
					case 10001:
						uni.showToast({
							title: res.data.toast,
							icon: 'none',
							success() {
								uni.reLaunch({
									url: '/pages/login/index'
								})
							}
						});
						break;
					case 10002:
						uni.showToast({
							title: res.data.toast,
							icon: 'none'
						});
						break;
					case 10004:
						uni.showToast({
							title: res.data.toast,
							icon: 'none'
						});
						break;
					default:
						tools.isFunction(cb) && cb(res.data);
				}
			}
		}
	});
}

function del(url, data, cb) {
	wx.request({
		url: url + queryData(data) + '&token=' + uni.getStorageSync('token'),
		method: 'delete',
		header: header,
		success: function(res) {
			tools.isFunction(cb) && cb(res.data);
		},
		fail(res) {}
	})
}

// 导出
module.exports = {
	url: url,
	get: get,
	post: post,
	delete: del
}
